import os
import time
import subprocess
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)

class GitAutoHandler(FileSystemEventHandler):
    def __init__(self, repo_path):
        self.repo_path = repo_path
        self.last_modified = 0
        self.cooldown = 2  # 冷却时间（秒）
        
    def on_modified(self, event):
        if event.is_directory:
            return
            
        current_time = time.time()
        if current_time - self.last_modified < self.cooldown:
            return
            
        self.last_modified = current_time
        
        # 获取相对路径
        try:
            abs_path = os.path.abspath(event.src_path)
            rel_path = os.path.relpath(abs_path, self.repo_path)
            
            # 忽略某些文件和目录
            if any(ignored in rel_path for ignored in [
                '.git', 'node_modules', '__pycache__', 
                '.idea', '.vscode', 'llama_index_dir'
            ]):
                return
                
            # 执行Git操作
            self._git_operations(rel_path)
        except Exception as e:
            logging.error(f"Error processing file {event.src_path}: {str(e)}")
    
    def _get_file_changes(self, file_path):
        """获取文件的具体更改内容"""
        try:
            # 获取文件更改的统计信息
            diff_stat = subprocess.run(
                ['git', 'diff', '--numstat', file_path],
                capture_output=True, text=True, check=True
            ).stdout.strip()
            
            if diff_stat:
                additions, deletions, _ = diff_stat.split('\t')
                changes_summary = f"+{additions}/-{deletions}"
            else:
                changes_summary = "new file"
                
            # 获取更改的具体内容摘要
            diff_content = subprocess.run(
                ['git', 'diff', '--unified=0', file_path],
                capture_output=True, text=True, check=True
            ).stdout.strip()
            
            # 提取更改的关键信息
            changes = []
            for line in diff_content.split('\n'):
                if line.startswith('+') and not line.startswith('+++'):
                    changes.append(line[1:].strip())
                elif line.startswith('-') and not line.startswith('---'):
                    changes.append(f"remove: {line[1:].strip()}")
                    
            # 限制更改描述的长度
            changes_desc = '; '.join(changes[:3])  # 只取前3个更改
            if len(changes) > 3:
                changes_desc += f" ... (+{len(changes)-3} more changes)"
                
            return f"{changes_summary} - {changes_desc}" if changes_desc else changes_summary
            
        except subprocess.CalledProcessError:
            return "unknown changes"
            
    def _git_operations(self, file_path):
        try:
            # 切换到仓库根目录
            os.chdir(self.repo_path)
            
            # 获取文件状态
            status = subprocess.run(['git', 'status', '--porcelain', file_path],
                                 capture_output=True, text=True).stdout.strip()
            
            if not status:
                return
                
            # 执行git add
            subprocess.run(['git', 'add', file_path], check=True)
            logging.info(f"Git add: {file_path}")
            
            # 获取更改内容摘要
            changes_summary = self._get_file_changes(file_path)
            
            # 执行git commit
            commit_msg = f"auto: {file_path}\n\nChanges: {changes_summary}"
            subprocess.run(['git', 'commit', '-m', commit_msg], check=True)
            logging.info(f"Git commit: {commit_msg}")
            
            # 执行git push
            subprocess.run(['git', 'push'], check=True)
            logging.info("Git push: successful")
            
        except subprocess.CalledProcessError as e:
            logging.error(f"Git operation failed: {str(e)}")
        except Exception as e:
            logging.error(f"Error during git operations: {str(e)}")

def main():
    # 获取项目根目录
    repo_path = subprocess.run(['git', 'rev-parse', '--show-toplevel'],
                             capture_output=True, text=True, check=True).stdout.strip()
    
    # 创建事件处理器和观察者
    event_handler = GitAutoHandler(repo_path)
    observer = Observer()
    observer.schedule(event_handler, repo_path, recursive=True)
    
    # 启动观察者
    observer.start()
    logging.info(f"Started watching repository: {repo_path}")
    
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
        logging.info("Stopped watching repository")
    
    observer.join()

if __name__ == "__main__":
    main() 